﻿
using System ;

using MskEdit.Sdk ;
using MskEdit.Dxf.Model ;


namespace MskEdit.Dxf.Backend
{

    public static class DxfDouble3dPointReader
    {
        internal static DxfDouble3dPoint TryReadAfterCode( DxfCode dxfCode, string[] allLines, ref int lineNo, DxfDouble3dPoint fallbackValue ) {
             
            int internalLineNo = lineNo ;
            
            double? x = DxfDoubleReader.TryReadAfterCode( allLines, ref internalLineNo, null ) ;
            if ( ! x.HasValue ) {
                SdkDiagnostics.TraceWarning( "Could not read X ordinate.", internalLineNo ) ;
                return fallbackValue ;
            }
            
            double? y = DxfDoubleReader.TryRead( ( dxfCode.Code + 10 ).ToString(), allLines, ref internalLineNo, null ) ;
            if ( ! y.HasValue ) {
                SdkDiagnostics.TraceWarning( "Could not read Y ordinate.", internalLineNo ) ;
                return fallbackValue ;
            }
            
            double? z = DxfDoubleReader.TryRead( ( dxfCode.Code + 20 ).ToString(), allLines, ref internalLineNo, 0 ) ;
            
                
            lineNo = internalLineNo ;
            
            return new DxfDouble3dPoint( x.Value, y.Value, z.Value ) ;
        }

            
        internal static DxfDouble3dPoint TryRead( string[] allLines, ref int lineNo, DxfDouble3dPoint fallbackValue ) {
        
            int internalLineNo = lineNo ;
            
            DxfCode dxfCode = DxfCodeReader.TryRead( allLines, ref internalLineNo, null ) ;
            if ( dxfCode == null )
                return fallbackValue ;
            
            if ( ! dxfCode.HasDouble3dPointCode )
                return fallbackValue ;
                
            internalLineNo += -1 ;
           
            DxfDouble3dPoint dxfPoint = TryReadAfterCode( dxfCode, allLines, ref internalLineNo, fallbackValue ) ;
            if ( dxfPoint == null ) {
                SdkDiagnostics.TraceWarning( "Failed to read DxfDouble3dPoint after code " + dxfCode.ToString(), internalLineNo ) ;
                return fallbackValue ;
            }            
                
            lineNo = internalLineNo ;
            
            return dxfPoint ;
        }

    }
}
